import pymongo
import pymysql
import redis
import yaml


class ConnectDataSource:
    def read_database_conf(self):
        with open("datasets.yaml") as f:
            datasrc = yaml.safe_load(f)
        return datasrc

    def connect_mysql(self):
        # 读取yaml文件获取数据源
        datasrc = self.read_database_conf()

        connection = pymysql.connect(host=datasrc["mysql"]["host"],
                                     port=datasrc["mysql"]["port"],
                                     user=datasrc["mysql"]["username"],
                                     # 因为密码是12345，转换成了数字12345，次数将类型转换为字符串
                                     password=str(datasrc["mysql"]["password"]),
                                     database='python15',
                                     charset='utf8mb4',
                                     cursorclass=pymysql.cursors.DictCursor)
        return connection

    def connect_redis(self):
        # 读取yaml文件获取数据源
        datasrc = self.read_database_conf()
        pool = redis.ConnectionPool(host=datasrc["redis"]["host"], port=datasrc["redis"]["port"],
                                    decode_responses=datasrc["redis"]["decode_responses"])
        r = redis.StrictRedis(connection_pool=pool)
        return r

    def connect_mongo(self):
        # 读取yaml文件获取数据源
        datasrc = self.read_database_conf()
        client = pymongo.MongoClient(
            host=datasrc["mongodb"]["host"],
            port=datasrc["mongodb"]["port"],
            # retryWrites=False
        )
        # 获取yaml文件中的db
        db_yaml = datasrc["mongodb"]["db"]
        mydb = client[db_yaml]
        if db_yaml == mydb.name:
            print("数据库连接成功")
            loger
        else:
            print("数据库未连接成功")

        coll_yaml = datasrc["mongodb"]["collection"]
        mycollection = mydb[coll_yaml]
        if coll_yaml == mycollection.name:
            print("集合切换成功")
        else:
            print("集合切换失败")
        return mycollection
